﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Xenta.Utils;
using Xenta.Attributes;
using Xenta.Web.Controllers;

namespace Xenta.Web.Areas.FileSystem.Controllers
{
    [Authenticate, InRole("ADMIN")]
    public sealed class GroupController : ExtController
    {
        #region GET/POST Actions

        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet, RestoreState]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost, PersistState]
        public ActionResult Create(int ownerID, string[] flags)
        {
            try
            {
                var m = Svc.ProcessOperation("CreateFileGroup", new
                {
                    OwnerID = ownerID,
                    Flags = flags.Merge(",")
                });
                return RedirectToAction(Loc.Act("Edit").Set(new
                {
                    id = JDM.Int32(m.EntityID)
                }));
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Create"));
        }

        [HttpGet, RestoreState]
        public ActionResult Edit(int id)
        {
            var m = Svc.ProcessOperation("GetFileGroup", new
            {
                EntityID = id,
                Fetch = "Entire"
            }, new
            {
                DisclosureLevel = "Entire"
            });
            if(m == null)
                return HttpNotFound();
            return View(m);
        }

        [HttpPost, PersistState]
        public ActionResult Update(int id, string[] flags)
        {
            try
            {
                Svc.ProcessOperation("UpdateFileGroup", new
                {
                    EntityID = id,
                    Flags = flags.Merge(",")
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }

            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpGet, PersistState]
        public ActionResult Delete(int id, bool deleteFiles)
        {
            try
            {
                Svc.ProcessOperation("DeleteFileGroup", new
                {
                    EntityID = id,
                    DeleteFiles = deleteFiles
                });
                return RedirectToAction(Loc.Act("Index"));
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpPost, PersistState]
        public ActionResult CreateTranslation(int groupID, int languageID, string name)
        {
            try
            {
                Svc.ProcessOperation("CreateFileGroupTranslation", new
                {
                    HolderID = groupID,
                    LanguageID = languageID,
                    Name = name
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id = groupID
            }));
        }

        [HttpPost, PersistState]
        public ActionResult UpdateTranslation(int id, int groupID, int languageID, string name)
        {
            try
            {
                Svc.ProcessOperation("UpdateFileGroupTranslation", new
                {
                    EntityID = id,
                    LanguageID = languageID,
                    Name = name
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id = groupID
            }));
        }

        [HttpGet, PersistState]
        public ActionResult DeleteTranslation(int id, int groupID)
        {
            try
            {
                Svc.ProcessOperation("DeleteFileGroupTranslation", new
                {
                    EntityID = id
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id = groupID
            }));
        }

        [HttpPost, PersistState]
        public ActionResult AddFile(int groupID, int fileID)
        {
            try
            {
                Svc.ProcessOperation("MapFileToGroup", new
                {
                    EntityID = groupID,
                    ChildID = fileID
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id = groupID
            }));
        }

        [HttpGet, PersistState]
        public ActionResult RemoveFile(int groupID, int fileID)
        {
            try
            {
                Svc.ProcessOperation("UnmapFileFromGroup", new
                {
                    EntityID = groupID,
                    ChildID = fileID
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id = groupID
            }));
        }

        #endregion

        #region AJAX Actions

        [HttpPost]
        public ActionResult Grid(int? page, 
            int? rows,
            string searchTerm,
            int? ownerID)
        {
            page = page.HasValue ? page.Value - 1 : 0;
            rows = rows.HasValue ? rows.Value : 30;

            var m = Svc.ProcessOperation("SearchFileGroups", new 
            {
                Term = new
                {
                    Expression = searchTerm
                },
                OwnerID = ownerID,
                Index = page * rows,
                Count = rows
            }, new
            {
                DisclosureLevel = "Extended",
                DisclosureOptions = new Dictionary<String, String>
                {
                    { "TranslatedTo", JDM.String(Svc.Localization.Language.Code) }
                }.Unload()
            });
            var data = new List<Object>();

            foreach(var i in m.Items)
            {
                var t = (i.Translations as IEnumerable<dynamic>)
                    .SingleOrDefault(x => JDM.Int32(x.Language.EntityID) ==
                        JDM.Int32(Svc.Localization.Language.EntityID));

                data.Add(new[] { 
                    JDM.Int32(i.EntityID),
                    JDM.String(i.Owner.Account.Email),
                    t != null ? JDM.String(t.Name) : String.Empty
                });
            }

            return Json(new
            {
                pageIndex = page + 1,
                pageCount = Math.Ceiling(JDM.Double(m.TotalCount) / rows),
                totalCount = JDM.Int64(m.TotalCount),
                data = data.ToArray()
            });
        }

        #endregion
    }
}
